#! /usr/bin/env python
#coding:utf-8

# alert check daemon
import sys
import os
import re
import json
import redis
import time
from datetime import datetime, date, timedelta
import urllib
import urllib2

reload(sys)
sys.setdefaultencoding('utf8')
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from config.tdm_config import *
import config.tdm_mongo_modules as tmm

'''
------------------------------------------------------------------------------
[UTIL] user util functions
------------------------------------------------------------------------------
'''
def AcardCtmLog_mongo_to_redis(r, ctmlog_obj, key, ex):
    try:
        val = ctmlog_obj.to_mongo().to_dict()
        del(val['city'])
        del(val['venue'])
        del(val['ctm'])
        del(val['_id'])
        val['class_date'] = val['class_date'].isoformat()
        val['log_tm'] = val['log_tm'].strftime("%Y-%m-%dT%H:%M:%S")
        val['ctm'] = ctmlog_obj.ctm.memo
        val['service_name'] = ctmlog_obj.venue.service_name
        r.set(key, json.dumps(val), ex=ex)
        '''
        {
            "port_3306": true,
            "service_name": null,
            "toattend": 0,
            "app_ver": "V1.0",
            "disk": 1.54,
            "noattend": 0,
            "attend_num": 0,
            "port_9100": true,
            "log_tm": "2015-10-26T10:30:07",
            "memory": 13.9,
            "status": true,
            "attend": 0,
            "crstatus": [
                {"status": true, "ip": "192.168.2.101"},
                {"status": true, "ip": "192.168.2.102"},
                {"status": true, "ip": "192.168.2.103"},
                {"status": true, "ip": "192.168.2.104"}
                ],
            "cli_ver": "1.8",
            "app_live": true,
            "master_slaver": true,
            "ip_100": false,
            "class_date": "1970-01-01T08:00:00",
            "ctm": "\u5907\u673a",
            "cpu": 4.0
        }
        '''
    except Exception as e:
        print "[ERROR]AcardCtmLog_mongo_to_redis:", str(e)

def AcardGetAutoCommand(r, city_name, venue_name, ctmdev_id):
    cmdkey = '%s:%s:%s:%s' % (tdm_redis_autocmd_prefix, city_name, venue_name, ctmdev_id)
    cmd = r.get(cmdkey)
    r.delete(cmdkey)
    if not cmd:
        return ''
    return cmd

def AcardSetAutoCommand(r, city_name, venue_name, ctmdev_id, command):
    cmdkey = '%s:%s:%s:%s' % (tdm_redis_autocmd_prefix, city_name, venue_name, ctmdev_id)
    cmd = r.set(cmdkey, command)

'''
根据城市获取教学点：工控机字典列表
'''
def AcardGetVenueListByCity(city):
    venue_list = {}
    for venue in city.venues:
        if venue.disabled:
            continue
        venue_list[venue.venue_id] = []
        for ctmdev in venue.ctm_devs:
            venue_list[venue.venue_id].append(ctmdev.devid)
    return venue_list

'''
根据城市获取教学点合并列表
'''
def AcardGetVenueGroupByCity(city):
    venue_group = []
    for vg in city.venuegroups:
        vg_list = [v.venue_id for v in vg.venues]
        venue_group.append(vg_list)
    return venue_group

'''
venue_ctmdev_list:
{
    'ff80808145d6e0b201466f9e1a4b55a7': 
        [
            '0512_zhongyanggy_dm_r1_attend',
            '0512_zhongyanggy_ds_r1_attend'
        ],
    'ff80808134e63d0f01352c5e15da64c0':
        [
            '0512_guanqianjie_dm_r1_attend',
            '0512_guanqianjie_ds_r1_attend'
        ],
    'ff808081410810e501411fa6d5505c44':
        [
            '0512_binhelu_dm_r1_attend',
            '0512_binhelu_ds_r1_attend',
            '0512_binhelu5_dm_r1_attend',
            '0512_binhelu5_ds_r1_attend'
        ]
}

venuegroup_list:
[
    [
        'ff80808145d6e0b201466f9e1a4b55a7',
        'ff80808134e63d0f01352c5e15da64c0'
    ],
    [
        'ff80808134e63d0f01352c5e15da64c0',
        'ff808081410810e501411fa6d5505c44'
    ]
]
'''

def acard_get_venue_by_ctmdevlist(venue_ctmdev_list, ctm_name):
    for venue, ctm_list in venue_ctmdev_list.iteritems():
        if ctm_name in ctm_list:
            return venue
    return None

def acard_get_group_venue_list(venue_group_list, venue_id):
    for venue_list in venue_group_list:
        if venue_id in venue_list:
            return venue_list
    return []

def acard_get_data_ctm(r, city_obj):
    #venue_sync_log:苏州:中央公园教学点:0512_zhongyanggy_ds_r1_attend
    attend_data_val = 0
    venue_list = {}

    # 用redis缓存的数据
    attend_data_key = '%s:%s:%s' % (tdm_data_key_attend, tdm_data_attend_ctm, city_obj.name)
    if r.exists(attend_data_key) and r.ttl(attend_data_key) > 120L:
        return r.get(attend_data_key)

    # 缓存失效，从redis中取数据
    venue_ctmdev_list = AcardGetVenueListByCity(city_obj)
    venuegroup_list = AcardGetVenueGroupByCity(city_obj)

    for venue in venue_ctmdev_list.keys():
        venue_list[venue] = False
    #print venue_list

    venue_data_name = '%s:%s:*' % (redis_venue_sync_log_prefix, city_obj.name)
    for ctm_key in r.keys(venue_data_name):
        ctm_data = json.loads(r.get(ctm_key))
        ctm_name = ctm_key.split(':')[3]
        if ctm_data.get('ip_100', False):
            #attend_data_val += ctm_data.get('toattend', 0)
            venue_id = acard_get_venue_by_ctmdevlist(venue_ctmdev_list, ctm_name)
            #print venue_id
            if not venue_list.has_key(venue_id):
                continue
            if not venue_list[venue_id]:
                attend_data_val += ctm_data.get('toattend', 0)
                venue_list[venue_id] = True
                venue_group = acard_get_group_venue_list(venuegroup_list, venue_id)
                for venue_group_id in venue_group:
                    venue_list[venue_group_id] = True
    #print venue_list
    #print 'attend_data_val', attend_data_val
    r.set(attend_data_key, attend_data_val, ex=600)
    return attend_data_val

def acard_get_venue_datalist_core(r, city_obj):
    attend_data_key = '%s:%s:%s' % (tdm_data_key_attend, tdm_data_attend_venue_core, city_obj.name)
    if r.exists(attend_data_key) and r.ttl(attend_data_key) > 120L:
        return json.loads(r.get(attend_data_key))

    _data = {}
    _data['areaCode'] = city_obj.zipcode
    _data['classDate'] = date.today().isoformat()
    data = urllib.urlencode(_data)

    rsp_obj = {}
    try:
        req = urllib2.Request(tdm_attend_from_core_url, data)
        rsp = urllib2.urlopen(req, timeout=10)
        rsp_obj = json.loads(rsp.read())
    except Exception as e:
        print "acard_get_venue_datalist_core error:", str(e)

    city_venue_data = rsp_obj.get('date')
    if not city_venue_data:
        city_venue_data = []
    r.set(attend_data_key, json.dumps(city_venue_data), ex=600)
    '''
    [[u'ff808081459772e70145ac5796bf76b7', 34], [u'ff80808149bf20610149c0f0ad340114', 102]]
    '''
    return city_venue_data

def acard_get_venue_data_core(r, city_obj, venue_obj):
    city_venue_data_dict = dict(acard_get_venue_datalist_core(r, city_obj))
    venuegroup_list = AcardGetVenueGroupByCity(city_obj)
    venue_group = acard_get_group_venue_list(venuegroup_list, venue_obj.venue_id)
    if not venue_group:
        return city_venue_data_dict.get(venue_obj.venue_id, 0)
    venuegroup_data = 0
    for venue_id in venue_group:
        venuegroup_data += city_venue_data_dict.get(venue_id, 0)
    return venuegroup_data


def acard_get_venue_data_ctm(r, city_obj, venue_obj):
    #venue_sync_log:苏州:中央公园教学点:0512_zhongyanggy_ds_r1_attend
    attend_data_val = 0
    venue_list = {}

    # 用redis缓存的数据
    attend_data_key = '%s:%s:%s:%s' % (tdm_data_key_attend, tdm_data_attend_venue_ctm, city_obj.name, venue_obj.name)
    if r.exists(attend_data_key) and r.ttl(attend_data_key) > 120L:
        return int(r.get(attend_data_key))

    venue_data_name = '%s:%s:%s:*' % (redis_venue_sync_log_prefix, city_obj.name, venue_obj.name)
    for ctm_key in r.keys(venue_data_name):
        ctm_data = json.loads(r.get(ctm_key))
        ctm_name = ctm_key.split(':')[3]
        if ctm_data.get('ip_100', False):
            attend_data_val = ctm_data.get('toattend', 0)

    r.set(attend_data_key, attend_data_val, ex=600)
    return attend_data_val


def acard_get_data_core(r, city_obj):
    attend_data_key = '%s:%s:%s' % (tdm_data_key_attend, tdm_data_attend_core, city_obj.name)
    if r.exists(attend_data_key) and r.ttl(attend_data_key) > 120L:
        return r.get(attend_data_key)

    # 缓存失效，从core取数据
    city_venue_data = acard_get_venue_datalist_core(r, city_obj)
    attend_data_val = sum([n[1] for n in city_venue_data])

    r.set(attend_data_key, attend_data_val, ex=600)
    return attend_data_val

def acard_get_data_yewu(r, city_obj):
    attend_data_key = '%s:%s:%s' % (tdm_data_key_attend, tdm_data_attend_yewu, city_obj.name)
    if r.exists(attend_data_key) and r.ttl(attend_data_key) > 120L:
        return r.get(attend_data_key)

    # 缓存失效，从业务系统取数据
    attend_data_val = 0
    headers = {
        'area': city_obj.zipcode
    }
    start_tm = date.today()
    end_tm = datetime(start_tm.year, start_tm.month, start_tm.day, 23, 59, 59)
    values = {
        'startTime': start_tm.strftime('%Y-%m-%d %H:%M:%S'),
        'endTime': end_tm.strftime('%Y-%m-%d %H:%M:%S')
    }

    rsp_obj = {}
    try:
        datas = urllib.urlencode(values)
        req = urllib2.Request(tdm_attend_from_register_url, datas, headers)
        rsp = urllib2.urlopen(req, timeout=30)
        rsp_obj = json.loads(rsp.read())
    except Exception as e:
        print "acard_get_data_yewu error:", str(e)

    if rsp_obj.get("rlt"):
        attend_data_val = rsp_obj.get('data', 0)
    else:
        print 'acard_get_data_yewu error:', rsp_obj.get('msg')

    r.set(attend_data_key, attend_data_val, ex=600)
    return attend_data_val


def acard_get_venuegroup_by_id(venue_id):
    _data = {
        'venueId': venue_id
    }
    data = urllib.urlencode(_data)

    rsp_obj = {}
    try:
        req = urllib2.Request(tdm_attend_venuegroup_url, data)
        rsp = urllib2.urlopen(req, timeout=5)
        rsp_obj = json.loads(rsp.read())
    except Exception as e:
        print "acard_get_venuegroup_by_id error:", str(e)

    if rsp_obj.get('success', False):
        return rsp_obj.get('data', [])
    return []

def acard_async_venue_group():
    city_venue_group = {}
    for city in tmm.City.objects():
        print city.name
        city_venue_group[city.name] = []
        for vg in city.venuegroups:
            city_venue_group[city.name].append(set([v.venue_id for v in vg.venues]))
        for venue in city.venues:
            print 'find group by:', venue.venue_id
            venue_group = acard_get_venuegroup_by_id(venue.venue_id)

            if len(venue_group) > 1:
                print 'find new group:', venue_group
                vg_set = set(venue_group)
                #print 'old groups:', city_venue_group[city.name]
                vg_exist = False
                for vg_i in city_venue_group[city.name]:
                    if not vg_i^vg_set:
                        vg_exist = True
                if not vg_exist:
                    vg_obj = tmm.VenueGroup()
                    for venue_id in venue_group:
                        venue_obj = tmm.Venue.objects(venue_id=venue_id).first()
                        if venue_obj:
                            vg_obj.venues.append(venue_obj)
                        else:
                            print 'ERROR! venue_id:%s is not exist' % (venue_id,)
                    vg_obj.save()
                    city.venuegroups.append(vg_obj)
                    city_venue_group[city.name].append(vg_set)
                    city.save()
                    print 'new VenueGroup', ','.join([v.name for v in vg_obj.venues])
                    vg_exist = True


        '''
        try:
            vg_obj = tmm.VenueGroup()
            for venue_id in venue_list:
                venue_obj = tmm.Venue.objects(venue_id=venue_id).first()
                vg_obj.venues.append(venue_obj)
            vg_obj.save()
            city_obj.venuegroups.append(vg_obj)
            city_obj.save()
            result.append("教学点合并成功")
        except Exception as e:
            errors.append("教学点合并失败")
        '''


if __name__ == '__main__':
    tmm.db_connect(tdm_mongo_acard_db)
    r = redis.Redis(host=tdm_redis_host, db=tdm_redis_db)
    '''
    city = tmm.City.objects(name='北京').first()
    yewu_num = acard_get_data_yewu(r, city)
    core_num = acard_get_data_core(r, city)
    ctm_num = acard_get_data_ctm(r, city)

    print 'yewu_num=', yewu_num
    print 'core_num=', core_num
    print 'ctm_num=', ctm_num
    '''
    acard_async_venue_group()
